<template>
  <el-dialog
      v-model="visibleProxy"
      :title="title"
      :width="width"
      draggable
  >
    <el-form :model="formData" :label-width="labelWidth" :style="{ width: formWidth }">
      <el-form-item
          v-for="col in columns"
          :key="col.prop"
          :label="col.label"
      >
        <template v-if="col.type === 'text'">
          <el-input v-model="formData[col.prop]" />
        </template>

        <template v-else-if="col.type === 'date'">
          <el-date-picker
              v-model="formData[col.prop]"
              type="date"
              placeholder="请选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
          />
        </template>

        <template v-else-if="col.type === 'select'">
          <el-select
              v-model="formData[col.prop]"
              placeholder="请选择"
              style="width: 100%"
              clearable
          >
            <el-option
                v-for="option in col.options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
            />
          </el-select>
        </template>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue';



const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  model: {
    type: Object,
    required: true
  },
  columns: {
    type: Array,
    required: true
  },
  title: {
    type: String,
    default: '编辑'
  },
  width: {
    type: String,
    default: '500px'
  },
  labelWidth: {
    type: String,
    default: '120px'
  },
  formWidth: {
    type: String,
    default: '100%'   // 默认撑满弹窗内部
  }
});

const emit = defineEmits(['update:visible', 'save']);
const formData = ref({});
watch(
    () => props.model,
    (newVal) => {
      formData.value = { ...newVal };
    },
    { immediate: true }
);

const visibleProxy = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
});

const cancel = () => {
  emit('update:visible', false);
};

const save = () => {
  emit('save', formData.value);
  emit('update:visible', false);
};
</script>
